// 内容脚本 - 注入到网页中

// 在视频播放器旁添加下载按钮
function addDownloadButton() {
    // 查找常见的视频播放器
    const videoElements = document.querySelectorAll('video');

    videoElements.forEach(video => {
        // 检查是否已添加按钮
        if (video.dataset.swiftshadowButton) {
            return;
        }

        // 创建下载按钮
        const button = document.createElement('button');
        button.textContent = '⬇️ 下载';
        button.style.cssText = `
      position: absolute;
      top: 10px;
      right: 10px;
      z-index: 9999;
      padding: 8px 16px;
      background: #FF4444;
      color: white;
      border: none;
      border-radius: 4px;
      cursor: pointer;
      font-size: 14px;
      box-shadow: 0 2px 8px rgba(0,0,0,0.3);
    `;

        button.addEventListener('click', () => {
            const videoUrl = video.src || video.currentSrc;

            if (videoUrl) {
                chrome.runtime.sendMessage({
                    action: 'downloadResource',
                    data: {
                        url: videoUrl,
                        title: document.title,
                        pageUrl: window.location.href
                    }
                });

                button.textContent = '✓ 已添加';
                setTimeout(() => {
                    button.textContent = '⬇️ 下载';
                }, 2000);
            }
        });

        // 将按钮添加到视频父容器
        const container = video.parentElement;
        if (container && getComputedStyle(container).position === 'static') {
            container.style.position = 'relative';
        }
        container.appendChild(button);

        video.dataset.swiftshadowButton = 'true';
    });
}

// 页面加载完成后执行
if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', addDownloadButton);
} else {
    addDownloadButton();
}

// 监听动态加载的视频
const observer = new MutationObserver(() => {
    addDownloadButton();
});

observer.observe(document.body, {
    childList: true,
    subtree: true
});

// 监听来自背景脚本的消息
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
    if (request.action === 'injectResults') {
        // 注入嗅探结果到页面（用于与Playwright集成）
        const resultDiv = document.createElement('div');
        resultDiv.id = 'swiftshadow-results';
        resultDiv.style.display = 'none';
        resultDiv.textContent = JSON.stringify(request.results);
        document.body.appendChild(resultDiv);

        sendResponse({success: true});
    }

    return true;
});